package com.qiche.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qiche.aspect.Result;
import com.qiche.mapper.MerchantMapper;
import com.qiche.mapper.StoreMemberMapper;
import com.qiche.mapper.WalletLogMapper;
import com.qiche.mapper.WalletMapper;
import com.qiche.model.Merchant;
import com.qiche.model.StoreMember;
import com.qiche.model.User;
import com.qiche.model.Wallet;
import com.qiche.model.WalletLog;
import com.qiche.requestpram.EnchashmentParam;
import com.qiche.service.EnchashmentService;
import com.qiche.util.ApiUtils;
import com.qiche.util.CodeGenerate;

import tk.mybatis.mapper.entity.Example;

/**
 * @author LB
 * @param <T>
 *
 * @date 2018年5月21日
 */
@Service("enchashmentService")
public class EnchashmentServiceImpl implements EnchashmentService{

	private static final Logger log = LoggerFactory.getLogger(EnchashmentServiceImpl.class);
	
	@Autowired
	private WalletLogMapper walletLogMapper;
	
	@Autowired
	private MerchantMapper merchantMapper;
	
	@Autowired
	private WalletMapper walletMapper;
	
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<?> enchashment(EnchashmentParam enchashmentParam)throws Exception {
			
			Example example = new Example(Wallet.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("merchantId", enchashmentParam.getMerchantId());
			Wallet wallet = walletMapper.selectOneByExample(example);
			int compareTo= wallet.getWalletBalance().compareTo(enchashmentParam.getAmount());
			if(compareTo==-1){
				return Result.createByErrorMessage("余额不足");
			}
			Merchant merchant= merchantMapper.selectByPrimaryKey(enchashmentParam.getMerchantId());
			if(StringUtils.isEmpty(merchant.getRcvAcctno())||StringUtils.isEmpty(merchant.getRcvAcctName())||StringUtils.isEmpty(merchant.getRcvBankNo())){
				return Result.createByErrorMessage("请先添加银行卡");
			}
			boolean addStatus = addWalletLogAndWallet(wallet,enchashmentParam,merchant);
			return Result.createBySuccess("申请体现成功，请耐心等待！",addStatus);
	}
	
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<?> AuditTransfer(String id ,String merchantId,Integer status) throws Exception {
			User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
			WalletLog walletLog= walletLogMapper.selectByPrimaryKey(id);
			if(walletLog==null||walletLog.getMerchantId()!=Integer.valueOf(merchantId)){
				return Result.createByErrorMessage("id参数有误！");
			}
			//商户信息
			Merchant merchant= merchantMapper.selectByPrimaryKey(merchantId);
			if(walletLog==null||merchant==null){
				return Result.createByErrorMessage("商家或提现数据异常");
			}
			walletLog.setStatus(status);
			walletLog.setId(Integer.valueOf(id));
			walletLog.setUpdateTime(new Date());
			walletLog.setAuditName(currentUser.getName()==null?"":currentUser.getName());
			int walletLogStatus =walletLogMapper.updateByPrimaryKeySelective(walletLog);
			if(status==-1||walletLogStatus<=0){
				return Result.createBySuccessMessage("审核不通过~！");
			}
			if(walletLogStatus>0){
				Wallet wallet = walletMapper.selectByPrimaryKey(walletLog.getWalletId());
				BigDecimal sum= walletLogMapper.selectSumByMerchantId(Integer.valueOf(merchantId));
				wallet.setWaitAuditSum(sum);
				walletMapper.updateByPrimaryKeySelective(wallet);
				Result<?> result= transfer(walletLog,merchant);
				return result;
			}
			return Result.createByErrorMessage("审核异常,未转账成功");
	}
	
	
	
	private Result<?> transfer(WalletLog walletLog, Merchant merchant)throws Exception{
		Map<String, Object> map = new HashMap<>();
		map.put("orderNo", walletLog.getOrderNumber());//订单号
		map.put("rcvAcctno",merchant.getRcvAcctno());//收款账号
		map.put("rcvAcctName", merchant.getRcvAcctName());//收款人姓名
		map.put("rcvAcctFlag", "1");
		//转账方式，可选值： 0 普通（小额） 1 加急（大额） 2 实时 “小额”转账单笔 5 万 元以下，7*24 小时非实 时到账；
		//“大额”转账单笔无限额 限制，实时到账，处理时 间为工作日 8:30~17:00； “实时”转账单笔 5 万 元以下，7乘以24 小时实时 到账；
		map.put("chnl", 0);
		map.put("rcvBankNo", merchant.getRcvBankNo());//联行号
		map.put("amount", walletLog.getSum());//金额
		log.info("============单笔转账参数:{}",map);
		Map<String, Object> transferMap= ApiUtils.transfer(map);
		log.info("============支付成功后的响应参数:{}",transferMap);
		if(transferMap.get("code").equals(2000)){
			return Result.createBySuccess("审核通过转账成功",transferMap);
		}
		throw new RuntimeException("支付服务异常异常");
	}
	
	/**
	 * 钱包和钱包日志变更
	 * @param walletLog
	 * @param wallet
	 * @param enchashmentParam
	 * @param merchant
	 * @return
	 */
	private boolean addWalletLogAndWallet(Wallet wallet,EnchashmentParam enchashmentParam,Merchant merchant)throws Exception{
		//剩余金额
		BigDecimal residue= wallet.getWalletBalance().subtract(enchashmentParam.getAmount()) ;
		WalletLog walletLog = new WalletLog();
		walletLog.setMerchantId(wallet.getMerchantId());
		walletLog.setOrderNumber(CodeGenerate.orderNumber());
		walletLog.setSum(enchashmentParam.getAmount());
		walletLog.setWalletId(wallet.getId());
		walletLog.setStatus(0);
		walletLog.setTradeAccount(merchant.getRcvAcctno());
		walletLog.setResidueAmount(residue);
		walletLog.setEnchashmentName(merchant.getContacts());
		walletLog.setCreateTime(new Date());
		int walletLogStatus = walletLogMapper.insert(walletLog);
		wallet.setWalletBalance(residue);
		wallet.setUpdateTime(new Date());
		BigDecimal sum= walletLogMapper.selectSumByMerchantId(merchant.getId().intValue());
		wallet.setWaitAuditSum(sum);
		wallet.setUpdateTime(new Date());
		int walletStatus = walletMapper.updateByPrimaryKeySelective(wallet);
		if(walletStatus!=1&&walletLogStatus!=1){			  
			throw new RuntimeException("申请取现写失败异常");
			}
		return true;
		
	}


}
